<?php
/**
 * WordPress Command Line Interface
 *
 * This script is designed to be run from the command line as a non-webserver
 * process, specifically for cron tasks. It is intended mainly as an interface
 * for specific CLI scripts, like the cli_reset_host.php script
 *
 * USAGE
 *  test:               php WP_ROOT/cli.php -t
 *  run:                php WP_ROOT/cli.php arg1 arg2
 *
 * NOTES
 *  Minimum PHP Version is set to 4.4.2. That limit is somewhat arbitrary as it
 *  has only been tested on that version.
 *
 * @package WordPress
 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @author	{@link http://klenwell.com/is Tom Atwell}
 * @copyright Copyright 2010       Tom Atwell <klenwell@gmail.com>
 *
 */


/**
 * Import Main Libraries
 */
$doc_root = dirname(__FILE__) . '/';
$inc_path = sprintf('%s:%s:', ini_get('include_path'), $doc_root);
ini_set('include_path', $inc_path);


/**
 * RequestHandler class
 * @this runs the script (see bottom of file)
 */
class RequestHandler {

    # configurable properties
    var $debug = 0;
    var $minimum_php_version = '4.4.2';
    var $pretty_print = 1;

    # non-configurable properties
    var $start_time = 0;

    function RequestHandler() {
        $this->start_time = microtime();
        $this->argv = $_SERVER['argv'];
    }

    function security_checks() {
        $this->cli_check();
        $this->sanity_checks();
    }

    function cli_check() {
        if ( ! php_sapi_name() == 'cli' ) {
            trigger_error('This script is accessible only from the PHP CLI.',
                          E_USER_ERROR);
        }
        define('WP_ALLOW_CLI', 1);
    }

    function sanity_checks() {
        # minimum version check
        if ( !function_exists('version_compare') ||
                version_compare(phpversion(),$this->minimum_php_version,'<') ) {
            $mt = 'Invalid PHP Version: either upgrade PHP to v.%s or try changing setting in %s';
            $php_version_error = sprintf($mt, $this->minimum_php_version, __FILE__);
            trigger_error($php_version_error, E_USER_ERROR);
        }
    }

    function parse_command_line()
    {
        $ShortOpts = array(
            'c:',   # config key ($_SERVER['SERVER_NAME'])
            't',    # test
        );

        $options = getopt(implode('',$ShortOpts));

        if ( isset($options['c']) ) {
            $_SERVER['SERVER_NAME'] = $options['c'];
        }

        if ( isset($options['t']) ) {
            $run_mode = 'test';
        }
        else {
            $run_mode = 'default';
        }

        $this->wikka_uri = array_pop($_SERVER['argv']);
        $this->basename = basename($_SERVER['argv'][0]);

        return $run_mode;
    }


    # output methods
    function output($content) {
        if ( $this->debug ) {
            $this->debug_output();
        }

        if ( $this->pretty_print ) {
            $this->pretty_print_output($content);
        }
        else {
            print $content;
        }

    }

    function debug_output() {
        $format_ = <<<HDOC
wikka cron script
-----------------
basename:           %s
php version:        %s
min php version:    %s
server time:        %s

argv:
%s

_SERVER:
%s

USAGE:
    php %s [-c CONFIG_KEY] arg1 arg2 [...]

script complete in %.4f s

HDOC;
        printf( $format_,
                $this->basename,
                phpversion(),
                $this->minimum_php_version,
                date('Y-m-d H:i:s'),
                print_r($this->argv,1),
                print_r($_SERVER,1),
                __FILE__,
                microtime() - $this->start_time );
    }

    function pretty_print_output($content) {
        $content = preg_replace('%<br[^>]*>|\n%', '***', $content);
        $content = preg_replace('%\s+%', ' ', $content);
        $content = str_replace('***', "\n", $content);
        $content = preg_replace('%\n{3,}%', "\n\n", $content);
        print $content;
    }


    # main methods
    function main_cli() {
        trigger_error('main_cli method should be overridden', E_USER_ERROR);
    }

    function test_cli() {
        $this->security_checks();
        $this->debug_output();
    }

    function main()
    {
        $run_mode = $this->parse_command_line();

        if ( $run_mode == 'test' ) {
            $this->test_cli();
        }
        else {
            $content = $this->main_cli();
            $this->output($content);
        }
    }
}


/**
 * main section: runs some debug code if this file is invoked directly in
 * browser or from command line
 */
$is_main_cli = isset($_SERVER['argv'][0]) && (realpath($_SERVER['argv'][0]) == __FILE__);
if ( $is_main_cli ) {
    $CliHandler = new RequestHandler();
    $CliHandler->main();
}

?>
